<template>
    <t-layout>
        <t-header>
            <t-space align="center">
                <t-select v-model="selected_config.grade" label="年级">
                    <t-option value="all">
                        【所有年级】
                    </t-option>
                    <t-option v-for="grade in available_config.grade" :value="grade">
                        {{ grade }}
                    </t-option>
                </t-select>
                <t-select v-model="selected_config.subject" label="学科">
                    <t-option value="all">
                        【所有学科】
                    </t-option>
                    <t-option v-for="subject in available_config.subjects" :value="subject">
                        {{ subject }}
                    </t-option>
                </t-select>
                <t-select v-model="selected_config.class_name" label="班级">
                    <t-option value="all">
                        【所有班级】
                    </t-option>
                    <t-option v-for="class_name in available_config.class_names" :value="class_name">
                        {{ class_name }}
                    </t-option>
                </t-select>
            </t-space>
        </t-header>
        <t-content>
            <t-alert theme="info" message="请在上方选择年级班级和科目" v-if="showSkeleton" />
            <t-skeleton :loading="showSkeleton">
            </t-skeleton>

            <div class="card-table-container" v-if="!showSkeleton">
                <table class="card-table" v-if="cards">
                    <thead>
                        <tr>
                            <th>年级</th>
                            <th>学科</th>
                            <th>班级</th>
                            <th>问题</th>
                            <th>答案</th>
                            <th>创建时间</th>
                            <th>上次复习时间</th>
                            <th>下次应复习时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="card in cards" :key="card.id">
                            <td>{{ card.grade }}</td>
                            <td>{{ card.subject }}</td>
                            <td>{{ card.class_name }}</td>
                            <td>{{ card.question }}</td>
                            <td>{{ card.answer || '无' }}</td>
                            <td>{{ convertUtcToLocal(card.create_time) }}</td>
                            <td>{{ card.last_review ? convertUtcToLocal(card.last_review) : '未复习' }}</td>
                            <td>{{ card.next_review ? convertUtcToLocal(card.next_review) : '未安排' }}</td>
                            <td>
                                <button class="delete-btn" @click="deleteCard(card.id)">删除</button>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <t-alert theme="info" message="暂无卡片" v-else />
            </div>
        </t-content>
    </t-layout>
</template>

<style scoped>
.card-table-container {
    margin: 20px;
    overflow-x: auto;
}

.card-table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 10px;
}

.card-table th,
.card-table td {
    border: 1px solid #ddd;
    padding: 8px;
    text-align: left;
}

.card-table th {
    background-color: #f2f2f2;
    position: sticky;
    top: 0;
}

.card-table tr:nth-child(even) {
    background-color: #f9f9f9;
}

.card-table tr:hover {
    background-color: #f1f1f1;
}

.delete-btn {
    background-color: #ff4d4f;
    color: white;
    border: none;
    padding: 5px 10px;
    border-radius: 4px;
    cursor: pointer;
}

.delete-btn:hover {
    background-color: #ff7875;
}
</style>
<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import axios from 'axios'
import { MessagePlugin } from 'tdesign-vue-next'

// 从本地存储加载配置
const loadConfigFromStorage = () => {
  const savedConfig = localStorage.getItem('listViewConfig')
  return savedConfig ? JSON.parse(savedConfig) : { grade: '', subject: '', class_name: '' }
}

// 保存配置到本地存储
const saveConfigToStorage = (config) => {
  localStorage.setItem('listViewConfig', JSON.stringify(config))
}

const selected_config = ref(loadConfigFromStorage())
//判断是否显示骨架屏
const showSkeleton = computed(() => {
    return !selected_config.value.grade || 
           !selected_config.value.subject || 
           !selected_config.value.class_name;
})
const available_config = ref({ grade: [], subject: [], class_name: [] })
const cards = ref([])

const loadAvailableConfig = async () => {
    try {
        const response = await axios.get('/api/config')
        available_config.value = response.data
    } catch (error) {
        console.error('Error fetching config:', error)
    }
}

const loadCards = async () => {
    try {
        const response = await axios.get('/api/list_cards', {
            params: {
                grade: selected_config.value.grade,
                subject: selected_config.value.subject,
                class_name: selected_config.value.class_name
            }
        })
        cards.value = response.data.cards
    } catch (error) {
        console.error('Error fetching cards:', error)
    }
}

const deleteCard = async (cardId) => {
    try {
        await axios.delete('/api/delete', { data: { id: cardId } })
        MessagePlugin.success('卡片已删除')
        cards.value = cards.value.filter(card => card.id !== cardId)
    } catch (error) {
        console.error('Error deleting card:', error)
    }
}

onMounted(() => {
    document.title = '卡片列表'
    loadAvailableConfig();
    loadConfigFromStorage();
    if (selected_config.value.grade && selected_config.value.subject && 
        selected_config.value.class_name) {
        loadCards()
    }
})

function convertUtcToLocal(utcString) {
    if(!utcString) return '';
    const date = new Date(utcString + 'Z');
    const daysDiff = Math.round((date - new Date())/(1000*60*60*24));
    return `${date.getMonth()+1}月${date.getDate()}日(${Math.abs(daysDiff)}天${daysDiff > 0 ? '后' : '前'})`;
}
// 当配置变化时获取卡片
// 修改watch监听，保存配置变更
watch(selected_config, (newVal) => {
  if (newVal.grade && newVal.subject && newVal.class_name) {
    loadCards()
    saveConfigToStorage(newVal)
  }
}, { deep: true })
</script>
